package com.bawei.module_detail.ui

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_common.entity.SendCommentBody
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_detail.adapter.CommentAdapter
import com.bawei.module_detail.databinding.FragmentCommentsBinding
import com.bawei.module_detail.intent.VideoDetailIntent
import com.bawei.module_detail.model.entity.ReplyBody
import com.bawei.module_detail.state.VideoDetailState
import com.bawei.module_detail.viewmodel.VideoDetailViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

private const val TAG = "CommentsFragment"
class CommentsFragment : BaseMVIFragment() {
    private lateinit var videoDetailViewModel: VideoDetailViewModel
    private val binding: FragmentCommentsBinding by lazy {
        FragmentCommentsBinding.inflate(layoutInflater)
    }
    private val commentAdapter = CommentAdapter()
    private var mPosition = 0
    private var check = false
    private var itemId = AuthMMKV.videoDetailId

    // 敏感词列表
    private val sensitiveWords = listOf("傻逼", "垃圾", "脏话","讨吃货","奶球货", "你妈", "艹你妈","大扳机") // 可自行扩展

    // 敏感词检测方法
    private fun containsSensitiveWord(text: String): Boolean {
        return sensitiveWords.any { text.contains(it, ignoreCase = true) }
    }

    override fun initView() {
        super.initView()
        binding.commentRv.adapter = commentAdapter
        binding.commentRv.layoutManager = LinearLayoutManager(requireContext())
        binding.commentRv.setItemViewCacheSize(20)
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel.intents.send(VideoDetailIntent.getCommentByUserId(0,if (itemId !=null)itemId else "7046176703973949964"))
            }
        }
        
        // 设置适配器点击事件
        commentAdapter.setOnItemClickListener { position, type ->
            mPosition = position
            check = true
            when (type) {
                0 -> { // 一级评论
                    val comment = commentAdapter.getComment(position)
                    if (comment != null) {
                        binding.sendCommentEt.hint = "回复${comment.nickname}"
                    }
                }
                1 -> { // 二级评论
                    val reply = commentAdapter.getReply(position)
                    if (reply != null) {
                        binding.sendCommentEt.hint = "回复${reply.nickname}"
                    }
                }
            }
        }
        
        commentAdapter.setOnItemLongClickListener { position, type ->
            when (type) {
                0 -> { // 一级评论
                    DeteleComment(position)
                }
                1 -> { // 二级评论
                    DeleteReply(position)
                }
            }
        }
        
        commentAdapter.setOnReplyClickListener { position ->
            mPosition = position
            check = true
            // 根据位置判断是评论还是回复
            val comment = commentAdapter.getComment(position)
            val reply = commentAdapter.getReply(position)
            
            if (comment != null) {
                binding.sendCommentEt.hint = "回复${comment.nickname}"
            } else if (reply != null) {
                binding.sendCommentEt.hint = "回复${reply.nickname}"
            }
        }
        
        commentAdapter.setOnLikeClickListener { position, type ->
            when (type) {
                0 -> { // 一级评论点赞
                    val comment = commentAdapter.getComment(position)
                    if (comment != null) {
                        // TODO: 实现评论点赞功能
                        ToastUtils.showLong( "评论点赞功能待实现")
                    }
                }
                1 -> { // 二级评论点赞
                    val reply = commentAdapter.getReply(position)
                    if (reply != null) {
                        // TODO: 实现回复点赞功能
                        ToastUtils.showLong( "回复点赞功能待实现")
                    }
                }
            }
        }
        
        // 设置加载更多点击事件
        commentAdapter.setOnLoadMoreClickListener {
            // TODO: 实现加载更多功能
            ToastUtils.showLong("加载更多功能待实现")
        }

        binding.sendCommentBtn.setOnClickListener {
            val content = binding.sendCommentEt.text.toString().trim()
            if (content.isEmpty()) {
                ToastUtils.showLong( "请输入评论内容")
                return@setOnClickListener
            }
            if (containsSensitiveWord(content)) {
                ToastUtils.showShort("评论包含敏感词，请修改后再发送")
                return@setOnClickListener
            }

            val string = AuthMMKV.username
            if (check){
                // 判断是回复评论还是回复回复
                val comment = commentAdapter.getComment(mPosition)
                val reply = commentAdapter.getReply(mPosition)
                
                if (comment != null) {
                    // 回复一级评论
                    val replyBody = ReplyBody(
                        agreenum = 200,
                        commentid = comment.id,
                        content = content,
                        createtime =  "${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())}",
                        id = 0,
                        nickname = string!!,
                        status = 0,
                        userid = 18,
                        userlogo = "",
                    )
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.STARTED){
                            videoDetailViewModel.intents.send(VideoDetailIntent.reply(replyBody))
                        }
                    }
                } else if (reply != null) {
                    // 回复二级评论（这里需要根据实际API调整）
                    ToastUtils.showLong("回复回复功能待实现")
                } else {
                    ToastUtils.showLong("评论不存在")
                    return@setOnClickListener
                }
                
                binding.sendCommentEt.text.clear()

            }else{
                // 发送一级评论
                val sendCommentBody = SendCommentBody(
                    itemid = if (itemId!=null)itemId else "7046705001120399908",
                    content = content,
                    userid = AuthMMKV.uId,
                    nickname = string!!,
                    userlogo = "",
                    createtime = "${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())}",
                    replytotal = 0,
                    agreenum = 0,
                    datatype = 0,
                    id = 0
                )
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED){
                        videoDetailViewModel.intents.send(VideoDetailIntent.sendComment(sendCommentBody))
                    }
                }
                binding.sendCommentEt.text.clear()
            }
        }
        
        // 设置搜索功能（如果有搜索框的话）
        // binding.searchEditText.addTextChangedListener(object : TextWatcher {
        //     override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        //     override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        //     override fun afterTextChanged(s: Editable?) {
        //         commentAdapter.filterComments(s?.toString() ?: "")
        //     }
        // })
    }
    
    override fun generateViewModel() {
        videoDetailViewModel = ViewModelProvider(this)[VideoDetailViewModel::class.java]
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel._simpleVideoCommentFlow.collect {
                    when(it){
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                            ToastUtils.showLong("获取评论失败：${it.msg}")
                        }
                        is VideoDetailState.VideoCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            commentAdapter.refreshCommentList(it.list!!)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel._simpleVideoDetailSendCommentFlow.collect {
                    when(it){
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                            ToastUtils.showLong( "发送评论失败：${it.msg}")
                        }
                        is VideoDetailState.SendCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong("评论发送成功")
                            videoDetailViewModel.intents.send(VideoDetailIntent.getCommentByUserId(0,if (itemId !=null)itemId else "7046176703973949964"))
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel._simpleVideoDetailOneDeleteFlow.collect {
                    when(it){
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                            ToastUtils.showLong( "删除评论失败：${it.msg}")
                        }
                        is VideoDetailState.DeleteCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong("删除成功")
                            videoDetailViewModel.intents.send(VideoDetailIntent.getCommentByUserId(0,if (itemId !=null)itemId else "7046176703973949964"))
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel._simpleVideoDetailComReplyDeleteFlow.collect {
                    when(it){
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                            ToastUtils.showLong("删除回复失败：${it.msg}")
                        }
                        is VideoDetailState.ReplyDeleteSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong("删除成功")
                            videoDetailViewModel.intents.send(VideoDetailIntent.getCommentByUserId(0,if (itemId !=null)itemId else "7046176703973949964"))
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                videoDetailViewModel._simpleVideoDetailComReplyFlow.collect {
                    when(it){
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                            ToastUtils.showLong( "回复评论失败：${it.msg}")
                        }
                        is VideoDetailState.ReplyCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            ToastUtils.showLong( "回复成功")
                            videoDetailViewModel.intents.send(VideoDetailIntent.getCommentByUserId(0,if (itemId !=null)itemId else "7046176703973949964"))
                            binding.sendCommentEt.hint = "来谈谈自己的看法吧~"
                            check = false
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }
    
    fun DeteleComment(index:Int){
        val comment = commentAdapter.getComment(index)
        if (comment == null) {
            ToastUtils.showLong("评论不存在")
            return
        }
        
        AlertDialog.Builder(requireContext())
            .setTitle("删除提醒")
            .setMessage("确定要删除${comment.nickname}的评论吗？")
            .setPositiveButton("确定"){dialog,_ ->
               lifecycleScope.launch {
                   repeatOnLifecycle(Lifecycle.State.STARTED){
                       videoDetailViewModel.intents.send(VideoDetailIntent.deleteComment(comment.id))
                   }
               }
                dialog.dismiss()
            }
            .setNegativeButton("取消"){item,_ ->
                item.dismiss()
            }
            .show()
    }
    
    fun DeleteReply(index: Int) {
        val reply = commentAdapter.getReply(index)
        if (reply == null) {
            ToastUtils.showLong( "回复不存在")
            return
        }
        
        AlertDialog.Builder(requireContext())
            .setTitle("删除提醒")
            .setMessage("确定要删除${reply.nickname}的回复吗？")
            .setPositiveButton("确定"){dialog,_ ->
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED){
                        videoDetailViewModel.intents.send(VideoDetailIntent.replyDelete(reply.id))
                    }
                }
                dialog.dismiss()
            }
            .setNegativeButton("取消"){item,_ ->
                item.dismiss()
            }
            .show()
    }
}